<template>
  <a-popover
    trigger="click"
    placement="right"
  >
    <!-- 头像触发区域 -->
    <template #default>
      <a-avatar
        :src="avatar_ref"
        :size="size"
        style="cursor: pointer"
        @click.stop
      />
    </template>
    <!-- 弹出卡片内容 -->
    <template #content>
      <div class="user-card-content">
        <a-avatar :src="avatar_ref" :size="48" />
        <div class="user-info">
          <div class="username">{{ username_ref }}</div>
          <div class="email">{{ email }}</div>
          <a-button type="primary" 
                v-if="!isSlef"
                @click="onFollowClick" 
                style="width: 100%;">
                {{ followText }}
            </a-button>
        </div>
        <div class="actions">
          <a-button type="link" @click="goToProfile">进入主页</a-button>
          <a-button type="link" @click="sendMessage">发送消息</a-button>
        </div>
      </div>
    </template>
  </a-popover>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ref, computed } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { getFollowStatus, follow, unfollow, getUserInfo } from '@/api/user'
import { getOrCreatePrivateSession } from '@/api/message'
import { useUserStore } from '@/stores/user'
import { useChatStore } from '@/stores/chat'
import  { onMounted, watch } from 'vue'
const userStore = useUserStore();
const chatStore = useChatStore();

const props = defineProps({
  avatar: {
    type: String,
    default: ''
  },
  username: {
    type: String,
    default: ''
  },
  email: {
    type: String,
    default: ''
  },
  size: {
    type: Number,
    default: 40
  }
})
const avatar_ref = ref(props.avatar)
const username_ref = ref(props.username)
const router = useRouter()
const following = ref(false)
const followers = ref(false)
const loading = ref(true)
const followText = computed(() => {
  if (!following.value) return '关注'
  if (following.value && !followers.value) return '已关注'
  if (following.value && followers.value) return '互相关注'
  return '关注'
})


const isSlef = computed(() => {
    return userStore.userStats.email === props.email;
})

async function fetchUserInfo() {
  loading.value = true
  try {
    const res = await getFollowStatus(props.email)
    following.value = res.following
    followers.value = res.followers
  } catch (error) {
    message.error(error)
  } finally {
    loading.value = false
  }
}
// 关注/取消关注按钮点击
async function onFollowClick() {
  if (!following.value) {
    // 关注
    try {
      const res = await follow(props.email)
      message.success(res.message)
      fetchUserInfo()
    } catch (error) {
      message.error(error)
    }

  } else {
    // 已关注/互相关注，弹窗确认
    Modal.confirm({
      title: '取消关注',
      content: '确定要取消关注该用户吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res = await unfollow(props.email)
          message.success(res.message)
          fetchUserInfo()
        } catch (error) {
          message.error(error)
        }
      }
    })
  }
}
function goToProfile() {
  router.push({ path: '/profile', query: { email: props.email } })
}
async function sendMessage() {
  try {
    const targetUserEmail = props.email
    
    // 调用API获取或创建会话
    const result = await getOrCreatePrivateSession(targetUserEmail)
    const { session_id, is_new, session_info } = result
    
    // 检查本地是否已存在该会话
    let existingSession = chatStore.sessionList.find(session => session.id === session_id)
    
    if (!existingSession) {
      // 创建新会话对象
      const newSession = {
        id: session_id,
        name: session_info.name || username_ref.value || targetUserEmail,
        is_group: false,
        avatar: session_info.avatar || avatar_ref.value,
        lastMsg: session_info.last_message || '',
        unread: session_info.unread_count || 0,
        updated_at: Date.now(),
        is_pinned: false
      }
      
      // 添加到会话列表
      chatStore.sessionList.unshift(newSession)
      
      // 初始化消息列表
      if (!chatStore.messagesMap[session_id]) {
        chatStore.messagesMap[session_id] = []
      }
      
      // 缓存用户信息
      await chatStore.fetchFriends(targetUserEmail)
    }
    
    // 设置为当前会话
    chatStore.handleSelectSession(session_id)
    
    // 跳转到聊天页面
    router.push('/chat')
    
    message.success(is_new ? '已创建新会话' : '已进入聊天界面')
  } catch (error) {
    console.error('获取会话失败:', error)
    message.error('获取会话失败: ' + error.message)
  }
}
</script>

<style scoped>
.user-card-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 200px;
}
.user-info {
  margin: 8px 0;
  text-align: center;
  flex-direction: column;
}
.username {
  font-weight: bold;
}
.email {
  color: #888;
  font-size: 12px;
}
.actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}
</style>